package com.lkd.handler;

import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-12-21 10:51
 */
@Component
@Topic(TopicConfig.VMS_RESULT_TOPIC)
@Slf4j
public class VendOutResultHandler implements MsgHandler {

    @Autowired
    private OrderService orderService;

    @Override
    public void process(String jsonMsg) throws IOException {

        //1.接收消息，判断消息参数
        VendoutResultContract orderCheck = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        if(orderCheck == null || orderCheck.getVendoutData() == null ||
                StringUtils.isEmpty(orderCheck.getVendoutData().getOrderNo())){
            return;
        }

        //2.修改状态
        OrderEntity orderEntity = orderService.getByOrderNo(orderCheck.getVendoutData().getOrderNo());
        if(orderEntity == null){
            log.error("出货结果-接收消息查询订单不存在" + jsonMsg);
            return;
        }

        if(orderCheck.isSuccess()){
            //成功
            orderEntity.setStatus(VMSystem.ORDER_STATUS_VENDOUT_SUCCESS);
        }else{
            //失败
            orderEntity.setStatus(VMSystem.ORDER_STATUS_VENDOUT_FAIL);

            //TODO 退款流程 课程中不涉及
        }

        orderService.updateById(orderEntity);
    }
}
